<template>
  <div class="feature-requests-container">
    <div class="feature-header">
      <h1 class="feature-title">功能请求</h1>
      <p class="feature-subtitle">查看并投票支持您喜欢的功能建议，或提交您自己的功能请求</p>
      
      <div class="feature-stats">
        <template v-if="loading">
          <div class="stats-placeholder">
            <n-skeleton height="80px" :repeat="1" />
          </div>
        </template>
        <template v-else>
          <div class="stats-item" v-for="stat in stats" :key="stat.status">
            <div class="stats-value">{{ stat.count }}</div>
            <div class="stats-label">{{ stat.text }}</div>
          </div>
          <div class="stats-divider"></div>
          <div class="stats-item votes-info">
            <div class="stats-value">{{ todayVotes }} / {{ maxVotesPerDay }}</div>
            <div class="stats-label">今日已投票 / 最大投票数</div>
          </div>
        </template>
      </div>
      
      <div class="feature-actions">
        <n-button type="primary" @click="$router.push({name: 'feature-submit'})">
          提交功能请求
        </n-button>
      </div>
    </div>
    
    <div class="feature-filters">
      <div class="filter-section">
        <n-space align="center">
          <span class="filter-label">状态：</span>
          <n-checkbox-group v-model:value="selectedStatus">
            <n-space>
              <n-checkbox v-for="item in statusOptions" :key="item.value" :value="item.value" :label="item.label" />
            </n-space>
          </n-checkbox-group>
        </n-space>
      </div>
      
      <div class="filter-section">
        <n-space align="center">
          <span class="filter-label">排序：</span>
          <n-select v-model:value="sortOption" :options="sortOptions" size="small" style="width: 160px" />
        </n-space>
      </div>
      
      <div class="filter-section search-section">
        <n-input-group>
          <n-input v-model:value="searchQuery" placeholder="搜索功能请求..." size="medium" clearable @keydown.enter="refreshList" />
          <n-button type="primary" @click="refreshList">
            搜索
          </n-button>
        </n-input-group>
      </div>
    </div>
    
    <div class="feature-list">
      <template v-if="loading && !featureRequests.length">
        <div v-for="i in 3" :key="i" class="skeleton-container">
          <n-skeleton height="180px" :repeat="1" />
        </div>
      </template>
      
      <template v-else-if="featureRequests.length">
        <FeatureCard 
          v-for="feature in featureRequests" 
          :key="feature.id" 
          :feature="feature"
          @voted="handleVoted"
        />
        
        <div class="pagination-container">
          <n-pagination
            v-model:page="currentPage"
            :page-count="totalPages"
            :page-size="pageSize"
            :item-count="totalItems"
            @update:page="handlePageChange"
          />
        </div>
      </template>
      
      <template v-else>
        <div class="empty-state">
          <n-empty description="暂无功能请求">
            <template #extra>
              <n-button type="primary" @click="$router.push({name: 'feature-submit'})">
                提交功能请求
              </n-button>
            </template>
          </n-empty>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useMessage } from 'naive-ui'
import { NButton, NCheckbox, NCheckboxGroup, NEmpty, NInput, NInputGroup, NPagination, NSelect, NSkeleton, NSpace } from 'naive-ui'
import FeatureCard from '@/components/feature/FeatureCard.vue'
import { getFeatureRequests, getFeatureRequestsStatus } from '@/api/feature'
import { FeatureRequest, FeatureRequestStatus } from '@/api/types/feature'

// 创建消息提示
const message = useMessage()

// 加载状态
const loading = ref(false)

// 功能请求列表
const featureRequests = ref<FeatureRequest[]>([])

// 统计数据
const stats = ref<{ status: string, text: string, count: number }[]>([])
const todayVotes = ref(0)
const maxVotesPerDay = ref(10)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

// 筛选选项，全部为字符串，与后端保持一致
const statusOptions = [
  { label: '已批准', value: FeatureRequestStatus.APPROVED },
  { label: '开发中', value: FeatureRequestStatus.IN_PROGRESS },
  { label: '已计划', value: FeatureRequestStatus.PLANNED },
  { label: '已完成', value: FeatureRequestStatus.COMPLETED }
]

// 默认选中项，全部为字符串
const selectedStatus = ref<string[]>([
  FeatureRequestStatus.APPROVED,
  FeatureRequestStatus.IN_PROGRESS,
  FeatureRequestStatus.PLANNED
])

// 排序选项
const sortOptions = [
  { label: '最多投票', value: 'votes_desc' },
  { label: '最少投票', value: 'votes_asc' },
  { label: '最新', value: 'newest' },
  { label: '最早', value: 'oldest' }
]
const sortOption = ref('newest')

// 搜索
const searchQuery = ref('')

// 加载功能请求列表
const loadFeatureRequests = async () => {
  loading.value = true
  
  try {
    const response = await getFeatureRequests({
      status: selectedStatus.value,
      search: searchQuery.value,
      sort: sortOption.value as any,
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (response.code === 1) {
      featureRequests.value = response.data.list
      totalItems.value = response.data.total
      
      // 获取今日投票数（如果API返回了这个字段）
      if ('today_votes' in response.data) {
        todayVotes.value = (response.data as any).today_votes || 0
      }
    } else {
      message.error(response.message || '获取功能请求失败')
    }
  } catch (error) {
    console.error('加载功能请求列表失败:', error)
    message.error('加载功能请求列表失败')
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await getFeatureRequestsStatus()
    
    if (response.code === 1) {
      // 适配统计数据结构
      if ('stats' in response.data) {
        stats.value = (response.data as any).stats || []
      } else {
        // 如果没有stats字段，则从各项数据中构建
        stats.value = [
          { status: 'total', text: '总计', count: response.data.total || 0 },
          { status: 'approved', text: '已批准', count: response.data.approved || 0 },
          { status: 'in_progress', text: '开发中', count: response.data.in_progress || 0 },
          { status: 'planned', text: '已计划', count: response.data.planned || 0 },
          { status: 'completed', text: '已完成', count: response.data.completed || 0 }
        ]
      }
      
      todayVotes.value = response.data.today_votes || 0
      
      if ('max_daily_votes' in response.data) {
        maxVotesPerDay.value = (response.data as any).max_daily_votes || 10
      }
    } else {
      message.error(response.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    message.error('加载统计数据失败')
  }
}

// 处理投票事件
const handleVoted = ({ id, votes }: { id: number, votes: number }) => {
  // 更新已投票功能的投票数
  const feature = featureRequests.value.find(f => f.id === id)
  if (feature) {
    feature.votes_count = votes
    feature.has_voted = true
    todayVotes.value++
  }
}

// 处理页码变更
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadFeatureRequests()
}

// 刷新列表
const refreshList = () => {
  currentPage.value = 1
  loadFeatureRequests()
}

// 监听筛选条件变化
watch([selectedStatus, sortOption], () => {
  refreshList()
})

// 组件挂载时加载数据
onMounted(() => {
  loadFeatureRequests()
  loadStats()
})
</script>

<style scoped>
.feature-requests-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.feature-header {
  margin-bottom: 2rem;
  text-align: center;
}

.feature-title {
  font-size: 2rem;
  font-weight: 700;
  color: var(--n-text-color-1);
  margin-bottom: 0.5rem;
}

.feature-subtitle {
  font-size: 1.125rem;
  color: var(--n-text-color-2);
  margin-bottom: 2rem;
}

.feature-stats {
  display: flex;
  justify-content: center;
  margin-bottom: 2rem;
  gap: 2rem;
  flex-wrap: wrap;
}

.stats-placeholder {
  width: 100%;
  max-width: 800px;
}

.stats-item {
  text-align: center;
}

.stats-value {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--n-text-color-1);
}

.stats-label {
  font-size: 0.875rem;
  color: var(--n-text-color-3);
}

.stats-divider {
  width: 1px;
  background-color: var(--n-border-color);
}

.votes-info {
  padding: 0 1rem;
  border-left: 1px solid #e5e7eb;
}

.feature-actions {
  margin-bottom: 2rem;
}

.feature-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 2rem;
  align-items: center;
}

.filter-section {
  margin-right: 1.5rem;
}

.filter-label {
  font-weight: 500;
  color: #4b5563;
}

.search-section {
  flex-grow: 1;
  min-width: 250px;
}

.feature-list {
  margin-top: 2rem;
}

.skeleton-container {
  margin-bottom: 1.5rem;
}

.pagination-container {
  margin-top: 2rem;
  display: flex;
  justify-content: center;
}

.empty-state {
  padding: 4rem 0;
  text-align: center;
}
</style> 